﻿1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#  train-model.py
#  
#  2022 Stephen Stengel <stephen.stengel@cwu.edu>
#  
#  Script to train a model with our dataset.
#  

print("Loading imports...")

import os
import skimage
import shutil
import matplotlib.pyplot as plt
from pathlib import Path
from tqdm import tqdm #Pretty loading bars

import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow import keras
from keras import callbacks


print("Done!")

## These global defines are copy pasted from the load-dataset.py
## Might be a more elegant way

DATASET_SAVE_DIR = "./dataset/"
TRAIN_SAVE_DIRECTORY = "./dataset/train/"
VAL_SAVE_DIRECTORY = "./dataset/val/"
TEST_SAVE_DIRECTORY = "./dataset/test/"

CLASS_INTERESTING = 0
CLASS_NOT_INTERESTING = 1

CLASS_INTERESTING_STRING = "interesting"
CLASS_NOT_INTERESTING_STRING = "not"

CLASS_NAMES_LIST_INT = [CLASS_INTERESTING, CLASS_NOT_INTERESTING]
CLASS_NAMES_LIST_STR = [CLASS_INTERESTING_STRING, CLASS_NOT_INTERESTING_STRING]

TEST_PRINTING = True


def main(args):
	print("hi")
	
	train, val, test, unscaledTest = getDatasets(TRAIN_SAVE_DIRECTORY, VAL_SAVE_DIRECTORY, TEST_SAVE_DIRECTORY)
	
	if TEST_PRINTING:
		printRandomSample(unscaledTest)
	
	shape = getPictureShape(test)
	print("the shape of the things: " + str(shape))
	
	# HARD CODED TO 150x150 right now!
	myModel = makeXceptionBasedModel()
	myHistory, myModel = trainModel(myModel, train, val)
	
	evaluateTraining(myHistory)
	
	evaluateModel(myModel, test)
	
	predictTestSet(myModel, test)
	
	print("DONE")


def predictTestSet(myModel, test):
	predictions = myModel.predict(test)
	score = predictions[0]


def evaluateModel(myModel, test):
	pass


def evaluateTraining(history):
	accuracy = history.history["accuracy"]
	val_accuracy = history.history["val_accuracy"]
	
	loss = history.history["loss"]
	val_loss = history.history["val_loss"]
	epochs = range(1, len(accuracy) + 1)
	plt.plot(epochs, accuracy, "o", label="Training accuracy")
	plt.plot(epochs, val_accuracy, "^", label="Validation accuracy")
	plt.title("Training and validation accuracy")
	plt.legend()
	plt.savefig("trainvalacc.png")
	plt.clf()
	
	plt.plot(epochs, loss, "o", label="Training loss")
	plt.plot(epochs, val_loss, "^", label="Validation loss")
	plt.title("Training and validation loss")
	plt.legend()
	plt.savefig("trainvalloss.png")
	plt.clf()


def getDatasets(trainDir, valDir, testDir):
	train = tf.data.experimental.load(trainDir)
	val = tf.data.experimental.load(valDir)
	test = tf.data.experimental.load(testDir)
	
	unscaledTest = test
	
	AUTOTUNE = tf.data.AUTOTUNE
	
	#Input needs to be scaled and shifted for xception.
	# ~ normalization_layer = tf.keras.layers.Rescaling(1.0 / 127.5, offset = -1)
	normalization_layer = tf.keras.layers.Rescaling(2.0, offset = -1) #this is lossy? #already scaled by load-dataset.py at the moment
	
	train = train.map(lambda x, y: (normalization_layer(x), y),  num_parallel_calls=AUTOTUNE)
	val = val.map(lambda x, y: (normalization_layer(x), y),  num_parallel_calls=AUTOTUNE)
	test = test.map(lambda x, y: (normalization_layer(x), y),  num_parallel_calls=AUTOTUNE)
	
	return train, val, test, unscaledTest
	

#Prints nine random images from the dataset.
def printRandomSample(in_ds):
	plt.figure(figsize=(10, 10))
	for img, label in in_ds.take(1):
		for i in tqdm(range(9)):
			ax = plt.subplot(3, 3, i + 1)
			myImg = np.asarray(img)
			plt.imshow(np.asarray(myImg[i]), cmap="gray")
			plt.title( CLASS_NAMES_LIST_STR[ np.asarray(label[i]) ]  )
			plt.axis("off")
		plt.show()
	
	plt.clf()


#get shape of pictures in model
def getPictureShape(in_ds):
	for img, label in in_ds.take(1):
		myImg = np.asarray(img)
		return np.asarray(myImg[0]).shape


#HARD CODED 150 RIGHT NOW
#imageShape is a tiple containing h w channels  (or was it w h channels? idk)
def makeXceptionBasedModel():
	base_model = keras.applications.Xception(
		weights="imagenet",  # Load weights pre-trained on ImageNet.
		input_shape=(150, 150, 3),
		include_top=False,
	)  # Do not include the ImageNet classifier at the top.
	
	# Freeze the base_model
	base_model.trainable = False
	
	print("Base model summary...")
	print(base_model.summary())
	
	# Rest of the model
	x = base_model.output
	x = layers.GlobalAveragePooling2D()(x)
	x = layers.Dense(4096, activation='relu')(x)
	# ~ x = layers.Dense(2, activation='sigmoid')(x)
	x = layers.Dense(2)(x)
	
	myModel = models.Model(inputs=base_model.input, outputs=x)
	
	myModel.compile(
			optimizer='adam',
			loss='sparse_categorical_crossentropy',
			metrics=['accuracy'])
	
	return myModel


def trainModel(model, train_ds, val_ds):
	checkpointFolder = "checkpoint/"
	
	checkpointer = callbacks.ModelCheckpoint(
			filepath = checkpointFolder,
			monitor = "accuracy",
			save_best_only = True,
			mode = "max")
	callbacks_list = [checkpointer]
		
	epochs = 10
	# ~ stepsPerEpoch = 10
	myHistory = model.fit(
			train_ds,
			epochs=epochs,
			# ~ steps_per_epoch = stepsPerEpoch,
			validation_data=val_ds,
			callbacks = callbacks_list)
	
	return myHistory, model
	



if __name__ == '__main__':
	import sys
	sys.exit(main(sys.argv))
